<template>
  <div>{{time}}</div>
</template>

<script>
export default {
  data() {
    return {
      time: '距离活动开始时间 00:00:00',
      flag: false,
    };
  },
  mounted() {
    const time = setInterval(() => {
      if (this.flag === true) {
        clearInterval(time);
      }
      this.timeDown();
    }, 500);
  },
  props: {
    endTime: {
      type: String,
    },
    startTime: {
      type: String,
    },
  },
  methods: {
    timeDown() {
      const endTime = new Date(this.endTime);
      const nowTime = new Date();
      const leftTime = Number.parseInt((endTime.getTime() - nowTime.getTime()) / 1000, 10);
      const d = Number.parseInt(leftTime / (24 * 60 * 60), 10);
      const h = this.formate(Number.parseInt((leftTime / (60 * 60)) % 24, 10));
      const m = this.formate(Number.parseInt((leftTime / 60) % 60, 10));
      const s = this.formate(Number.parseInt(leftTime % 60, 10));
      if (leftTime <= 0) {
        this.flag = true;
        this.$emit('time-end');
      }
      if (endTime > nowTime) {
        this.time = `${d}天${h}小时${m}分${s}秒`;
      }
    },
    formate(time) {
      if (time >= 10) {
        return time;
      }
      return `0${time}`;
    },
  },
};
</script>
